from django.shortcuts import render
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework.mixins import ListModelMixin
from rest_framework.generics import GenericAPIView, ListAPIView, CreateAPIView
from rest_framework_extensions.cache.mixins import CacheResponseMixin

# Create your views here.
from .models import HeadLineNews, NewsComment
from . import serializers


class HeadLineViewSet(CacheResponseMixin,ReadOnlyModelViewSet):
    """新闻列表序列化器,使用缓存减少对mysql的访问"""
    # queryset = HeadLineNews.objects.filter(is_delete=False).select_related('user').order_by("-create_time")

    def get_queryset(self):
        category_id = self.request.query_params.get('category_id',0)
        print(category_id)
        if int(category_id):
            return HeadLineNews.objects.filter(is_delete=False,category_id=category_id).select_related('user').order_by("-create_time")
        return HeadLineNews.objects.filter(is_delete=False).select_related('user').order_by("-create_time")

    def get_serializer_class(self):
        if self.action == 'list':
            return serializers.HeadLineNewsUserSerializer
        else:
            return serializers.HeadLineNewsDetailUserSerializer


class SubmitNewsView(CreateAPIView):
    """提交新闻视图"""

    permission_classes = [IsAuthenticated]

    serializer_class = serializers.SubmitNewsSerializer


class NewsCommentView(ListAPIView):
    """新闻评论视图"""
    def get_queryset(self):
        news_id = self.kwargs['news_id']
        # print(news_id)
        comment_news = NewsComment.objects.filter(headlinenews=news_id).select_related('user').order_by("-create_time")

        return comment_news

    serializer_class = serializers.NewscommentNewscommentSerializer


class SubmitNewsCommentView(CreateAPIView):
    """提交评论视图"""

    permission_classes = [IsAuthenticated]

    serializer_class = serializers.SubmitNewsCommentSerializer



